﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using MM.DBUtility;

namespace MobileManager
{
    public partial class MruleManageAdd : System.Web.UI.Page
    {
        private MM.Model.T_Users userModel;
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session["CurUser"] == null)
                {
                    Response.Redirect("Login.aspx");
                    return;
                }
                else
                {
                    userModel = (MM.Model.T_Users)Session["CurUser"];
                }
                if (!IsPostBack)
                {
                    BindDdlChannel(ref ddlChannel);
                    BindDdlODEP(ref ddlODEP);

                    BindProvice(ddlChannel.SelectedValue);
                    BindCustomer();

                    if (ddlODEP.Items.Count <= 0 || ddlChannel.Items.Count <= 0)
                        btnSave.Visible = false;
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region UserControl Bind
        private void BindProvice(string strNO)
        {
            cblProvince.Items.Clear();
            DataTable dt = DbHelperSql.Query(string.Format("SELECT TOP 1 ChannelPro,ONO FROM T_Channel WITH(NOLOCK) WHERE ChannelNO='{0}'", strNO)).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                string strPros = dt.Rows[0]["ChannelPro"].ToString().Replace(";", ",");
                strPros = strPros.Remove(strPros.LastIndexOf(","));
                cblProvince.DataSource = DbHelperSql.Query(string.Format("SELECT * FROM T_Province WITH(NOLOCK) WHERE ProvinceID IN ({0})", strPros)).Tables[0];
                cblProvince.DataValueField = "ProvinceID";
                cblProvince.DataTextField = "ProvinceName";
                cblProvince.DataBind();

                ddlODEP.SelectedValue = dt.Rows[0]["ONO"].ToString();
            }
        }
        private void BindCustomer()
        {
            cblCustomer.Items.Clear();
            cblCustomer.DataSource = DbHelperSql.Query("SELECT CNO,CNO+'-'+ CName as Name FROM T_Customers WITH(NOLOCK) ").Tables[0];
            cblCustomer.DataValueField = "CNO";
            cblCustomer.DataTextField = "Name";
            cblCustomer.DataBind();
        }
        private void BindDdlODEP(ref DropDownList ddl)
        {
            ddl.DataSource = DbHelperSql.Query("SELECT ONO,ONO+'-'+ OName as Name FROM T_ODEP WITH(NOLOCK) ").Tables[0];
            ddl.DataValueField = "ONO";
            ddl.DataTextField = "Name";
            ddl.DataBind();
        }
        private void BindDdlChannel(ref DropDownList ddl)
        {
            ddl.DataSource = DbHelperSql.Query("SELECT ChannelNO,ChannelNO+'-'+ ChannelNumber+'-'+ChannelOrder as Name FROM T_Channel WITH(NOLOCK) WHERE flag='0' order by ChannelNO").Tables[0];
            ddl.DataValueField = "ChannelNO";
            ddl.DataTextField = "Name";
            ddl.DataBind();
        }
        #endregion

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtCount.Text.Trim()))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "发送条数不能为空！");
                    return;
                }
                if (string.IsNullOrEmpty(inputDate.Value.Trim()))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "下次联网时间不能为空！");
                    return;
                }

                string strPros = string.Empty;
                for (int i = 0; i < cblProvince.Items.Count; i++)
                {
                    if (cblProvince.Items[i].Selected)
                        strPros += cblProvince.Items[i].Value + ",";
                }
                if (string.IsNullOrEmpty(strPros))
                {
                    MM.Common.Common.PageStartAlert(this.Page, "必须选择省份！");
                    return;
                }

                ArrayList alSQL = new ArrayList();
                ArrayList alSQL1 = new ArrayList();
                string[] argPros = strPros.Remove(strPros.LastIndexOf(",")).Split(',');
                for (int i = 0; i < cblCustomer.Items.Count; i++)
                {
                    if (cblCustomer.Items[i].Selected)
                    {
                        for (int j = 0; j < argPros.Length; j++)
                        {
                            if (BLSqlData.ExistRules(argPros[j], ddlODEP.SelectedValue, cblCustomer.Items[i].Value))
                            {
                                alSQL.Add(string.Format("DELETE FROM T_Rules WHERE ProvinceID={0} AND ONO='{1}' AND CNO='{2}'", argPros[j], ddlODEP.SelectedValue, cblCustomer.Items[i].Value));
                                alSQL1.Add(string.Format("insert into T_Rules(ProvinceID,ONO,CNO,ChannelNO,SendCount,NextTime,Status,TimeInterval) values({0},'{1}','{2}','{3}',{4},'{5}','{6}','{7}')", argPros[j], ddlODEP.SelectedValue, cblCustomer.Items[i].Value, ddlChannel.SelectedValue, txtCount.Text.Trim(), inputDate.Value.Trim(), ddlStatus.SelectedValue, txtTimeInterval.Text.Trim()));
                            }
                            else
                            {
                                alSQL1.Add(string.Format("insert into T_Rules(ProvinceID,ONO,CNO,ChannelNO,SendCount,NextTime,Status,TimeInterval) values({0},'{1}','{2}','{3}',{4},'{5}','{6}','{7}')", argPros[j], ddlODEP.SelectedValue, cblCustomer.Items[i].Value, ddlChannel.SelectedValue, txtCount.Text.Trim(), inputDate.Value.Trim(), ddlStatus.SelectedValue, txtTimeInterval.Text.Trim()));
                            }
                        }
                    }
                }

                if (alSQL.Count <= 0 && alSQL1.Count <= 0)
                {
                    MM.Common.Common.PageStartAlert(this.Page, "必须选择客户编号！");
                    return;
                }

                MM.DBUtility.DbHelperSql.ExecuteSqlTran(alSQL);
                MM.DBUtility.DbHelperSql.ExecuteSqlTran(alSQL1);
                MM.Common.Common.PageAlertAndRedirect(this.Page, "添加成功！", "MruleManage.aspx");
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        protected void ddlChannel_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindProvice(ddlChannel.SelectedValue);
        }
    }
}
